﻿using Newtonsoft.Json;
using System;
using System.Text;

namespace MQTT.Share.MQTT.Message
{
    public class MqttMessage
    {
        public string Topic { get; set; }

        public string Body { get; set; }

        public string ClientId { get; set; }

        public static T GetBody<T>(byte[] payload)
        {
            return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(payload));
        }
        public static bool TryGetBody<T>(byte[] payload, out T t) where T : class
        {
            try
            {
                t = GetBody<T>(payload);
            }
            catch (Exception)
            {
                t = null;
                return false;
            }

            return true;
        }

        public static T GetBodyByString<T>(string body)
        {
            return JsonConvert.DeserializeObject<T>(body);
        }

        public static bool TryGetBodyByString<T>(string body, out T t) where T : class
        {
            try
            {
                t = GetBodyByString<T>(body);
            }
            catch (Exception e)
            {
                t = null;
                return false;
            }
            return true;
        }

    }
}
